package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.tool.utils.Func;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVO;
import com.atguigu.gulimall.product.vo.AttrRespVO;
import com.atguigu.gulimall.product.vo.AttrVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品属性
 *
 * @author wenchao.long
 * @email wenchao.long@gmail.com
 * @date 2021-06-12 22:51:26
 */
@Service("attrService")
@AllArgsConstructor
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    private final AttrAttrgroupRelationService attrAttrgroupRelationService;

    private final AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    private final AttrGroupService attrGroupService;

    private final CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        save(attrEntity);

        // 保存关联关系
        if (Objects.equals(attr.getAttrType(), ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationService.save(relationEntity);
        }

    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId) {
        String key = (String) params.get("key");
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                Wrappers.<AttrEntity>lambdaQuery()
                        .eq(catelogId != 0, AttrEntity::getCatelogId, catelogId)
                        .and(Func.isNotBlank(key), i -> i.like(AttrEntity::getAttrName, key)
                                .or()
                                .eq(AttrEntity::getAttrId, key)
                        )
        );

        return getPageUtils(page);
    }

    @Override
    public AttrRespVO getAttrInfo(Long attrId) {
        AttrEntity entity = getById(attrId);
        AttrRespVO respVO = new AttrRespVO();
        BeanUtils.copyProperties(entity, respVO);

        if (Objects.equals(entity.getAttrType(), ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())) {
            // 1. 设置分组信息
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(
                    Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                            .eq(AttrAttrgroupRelationEntity::getAttrId, attrId)
            );
            Optional.ofNullable(relationEntity)
                    .ifPresent(r -> {
                        respVO.setAttrGroupId(r.getAttrGroupId());
                        AttrGroupEntity attrGroupEntity = attrGroupService.getById(r.getAttrGroupId());

                        Optional.ofNullable(attrGroupEntity).ifPresent(a -> respVO.setGroupName(a.getAttrGroupName()));
                    });
        }


        // 2. 设置分类信息
        Long catelogId = entity.getCatelogId();
        Optional.ofNullable(catelogId)
                .ifPresent(c -> {
                    Long[] catelogPath = categoryService.findCatelogPath(c);
                    respVO.setCatelogPath(catelogPath);

                    CategoryEntity categoryEntity = categoryService.getById(c);
                    Optional.ofNullable(categoryEntity).ifPresent(c1 -> respVO.setCatelogName(categoryEntity.getName()));

                });

        return respVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDetail(AttrVO attr) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr, entity);
        updateById(entity);

        if (Objects.equals(entity.getAttrType(), ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())) {
            // 1. 修改分组关联
            int count = attrAttrgroupRelationService.count(Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId())
            );
            if (count > 0) {
                attrAttrgroupRelationService.update(
                        Wrappers.<AttrAttrgroupRelationEntity>lambdaUpdate()
                                .set(AttrAttrgroupRelationEntity::getAttrGroupId, attr.getAttrGroupId())
                                .eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId())
                );
            } else {
                Optional.ofNullable(attr.getAttrGroupId()).ifPresent(a ->
                        attrAttrgroupRelationService.save(AttrAttrgroupRelationEntity.builder()
                                .attrId(attr.getAttrId())
                                .attrGroupId(a)
                                .build()
                        )
                );
            }
        }

    }

    @Override
    public PageUtils querySaleAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        String key = (String) params.get("key");
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                Wrappers.<AttrEntity>lambdaQuery()
                        .eq(catelogId != 0, AttrEntity::getCatelogId, catelogId)
                        .eq(AttrEntity::getAttrType, "base".equalsIgnoreCase(attrType)
                                ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode())
                        .and(Func.isNotBlank(key), i -> i.like(AttrEntity::getAttrName, key)
                                .or()
                                .eq(AttrEntity::getAttrId, key)
                        )
        );

        return getPageUtils(page);
    }

    /**
     * 根据分组id查找管理的所有基本属性
     *
     * @param attrgroupId 分组id
     * @return attrEntity
     */
    @Override
    public List<AttrEntity> getAttrRelation(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationService.list(
                Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                        .eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrgroupId)
        );

        List<Long> attrIds = entities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        if (Func.isEmpty(attrIds)) {
            return new ArrayList<>();
        }
        Collection<AttrEntity> attrEntities = listByIds(attrIds);
        return new ArrayList<>(attrEntities);
    }

    @Override
    public void deleteRelation(AttrGroupRelationVO[] attrGroupRelationVO) {
        List<AttrAttrgroupRelationEntity> entityList = Arrays.stream(attrGroupRelationVO)
                .map(item -> AttrAttrgroupRelationEntity.builder()
                        .attrGroupId(item.getAttrGroupId())
                        .attrId(item.getAttrId())
                        .build())
                .collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(entityList);

    }

    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> params) {
        IPage<AttrEntity> resPage = new Page<>();
        // 1. 当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity groupEntity = attrGroupService.getById(attrgroupId);
        Long catelogId = groupEntity.getCatelogId();
        // 2. 当前分组只能关联别的分组没有引用的属性
        // 2.1 当前分类下的其他分组
        if (catelogId != null) {
            List<AttrGroupEntity> groupEntities = attrGroupService.list(
                    Wrappers.<AttrGroupEntity>lambdaQuery()
                            .eq(AttrGroupEntity::getCatelogId, catelogId)
            );
            List<Long> groupIds = groupEntities.stream()
                    .map(AttrGroupEntity::getAttrGroupId)
                    .collect(Collectors.toList());

            // 2.2 这些分组关联的属性
            if (Func.isNotEmpty(groupIds)) {
                List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationService.list(
                        Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                                .in(AttrAttrgroupRelationEntity::getAttrGroupId, groupIds)
                );

                List<Long> attrIds = relationEntityList.stream()
                        .map(AttrAttrgroupRelationEntity::getAttrId)
                        .collect(Collectors.toList());

                String key = (String) params.get("key");

                // 2.3 从当前分类的所有属性中移除这些属性
                resPage = page(
                        new Query<AttrEntity>().getPage(params)
                        , Wrappers.<AttrEntity>lambdaQuery()
                                .eq(AttrEntity::getCatelogId, catelogId)
                                .eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())
                                .notIn(Func.isNotEmpty(attrIds), AttrEntity::getAttrId, attrIds)
                                .and(Func.isNotBlank(key),
                                        i -> i.eq(AttrEntity::getAttrId, key)
                                                .like(AttrEntity::getAttrName, key)
                                )
                );
            }

        }


        return new PageUtils(resPage);
    }

    private PageUtils getPageUtils(IPage<AttrEntity> page) {
        PageUtils pageUtils = new PageUtils(page);

        List<AttrEntity> records = page.getRecords();

        List<AttrRespVO> resList = records.stream().map(attrEntity -> {
            AttrRespVO attrRespVO = new AttrRespVO();
            BeanUtils.copyProperties(attrEntity, attrRespVO);
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId())
            );

            Optional.ofNullable(relationEntity).ifPresent(r -> {
                AttrGroupEntity groupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                Optional.ofNullable(groupEntity).ifPresent(g -> attrRespVO.setGroupName(groupEntity.getAttrGroupName()));

            });

            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            Optional.ofNullable(categoryEntity).ifPresent(c -> attrRespVO.setCatelogName(c.getName()));

            return attrRespVO;
        }).collect(Collectors.toList());

        pageUtils.setList(resList);
        return pageUtils;
    }

}
